package com.xkstream.client.utils;


import com.xkstream.client.api.API;
import com.xkstream.client.application.Application;
import com.xkstream.client.entity.User;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * Created by xiaoyi on 2017/5/17.
 */

public class RetrofitUtil {
    private RetrofitUtil() {
    }

    public static Retrofit getRetrofit() {
        return new Retrofit.Builder()
                .baseUrl(API.HOST)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                /*.addConverterFactory(ScalarsConverterFactory.create())*/
                .client(generateOkHttpClient())
                .build();
    }


    public static Retrofit getRetrofit(String baseUrl) {
        return new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                /*.addConverterFactory(ScalarsConverterFactory.create())*/
                .client(generateOkHttpClient())
                .build();
    }

    private static OkHttpClient generateOkHttpClient() {
        return new OkHttpClient.Builder().addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request()
                        .newBuilder()
                        .addHeader("User-Agent", DeviceUtils.getUserAgent())
                        .build();
                Response response = null;
                try {
                    request = addPublic(request);
                    response = chain.proceed(request);
                } catch (Exception e) {
                    L.e("RetrofitUtil", e.toString());
                }

                L.e("RetrofitUtil", "url\n" + getUrl(request.url().toString(), request.body()));
                return response;
            }

            private Request addPublic(Request oldRequest) {
                if (Application.getUser() != null && !oldRequest.url().toString().contains("login.do")
                        && oldRequest.toString().contains(API.HOST)) {
                    User user = Application.getUser();
                    HttpUrl.Builder builder = oldRequest.url()
                            .newBuilder()
                            .setEncodedQueryParameter("token", user.getToken());
                    Request newRequest = oldRequest.newBuilder()
                            .method(oldRequest.method(), oldRequest.body())
                            .url(builder.build())
                            .build();

                    return newRequest;
                } else {
                    return oldRequest;
                }

            }

        }).addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                .build();
    }

    private static String getUrl(String url, RequestBody body) {
        if (url.endsWith("?")) {
            url = url.substring(0, url.length() - 1);
        }
        StringBuilder sb = new StringBuilder(url);
        if (!sb.toString().contains("?")) {
            sb.append("?");
        } else {
            sb.append("&");
        }
        if (body instanceof FormBody)
            for (int i = 0; i < ((FormBody) body).size(); i++) {
                sb.append(((FormBody) body).encodedName(i)).append("=").append(((FormBody) body).encodedValue(i)).append("&");
            }
        return sb.toString().substring(0, sb.length() - 1);
    }


}
